#include "str.h"

bool str_has_prefx ( char * str, char * prefx ) {
	int len = strlen( prefx );
	if ( len > strlen( str ) ) {
		return false;
	}
	int i = 0;
	while ( i < len ) {
		if ( str[ i ]  != prefx[ i ] ) {
			return false;
		}
		i += 1;
	}
	return true;
}

bool str_has_suffx( char * str, char * suffx )
{
	int suffx_len = strlen( suffx );
	int str_len = strlen( str );
	if ( suffx_len > str_len ) {
		return false;
	}
	int i = 0;
	while ( i < suffx_len ) {
		if ( str[ str_len - suffx_len + i ] != suffx[ i ] ) {
			return false;
		}
		i += 1;
	}
	return true;
}

char * append_str( char * str1, char * str2 ) {
	int size = strlen( str1 ) + strlen( str2 );
	int len1 = strlen( str1 );
	char * joined =  alloca( ( len1 + strlen( str2 ) ) * sizeof( char ) );
	int count = 0;
	while ( count < size ) {
		if ( count < len1 ) {
			joined[ count ] = str1[ count ];
		}
		else {
			joined[ count ] = str2[ count - len1 ];
		}
		count += 1;
	}
	return joined;
}

bool str_has_str( char * str, char * part ) {
	int i = 0;
	int len = strlen( str );
	int len_part = strlen( part );
	while ( i < len ) {
		if ( str[ i ] == part[ 0 ] ) {
			int j = 0;
			while ( j < len_part ) {
				if ( str[ i + j ] == part[ j ] ) {
					j += 1;
				}
				else {
					break;
				}
			}
			return true;
		}
		else {
			i += 1;
		}
	}
	return false;
}

int start_of_str ( char * part, char * str ) {
	if( strlen( part )  > strlen( str ) ) {
		return -1;
	}
	const int max = strlen( str ) - strlen ( part );
	int plen = strlen( part) ;
	int i = 0; //counter 1
	int j = 0; // counter 2
	int tf = 0; // true/false
	while( i <= max ) {
		tf = 0;
		while( j < plen ) {
			if ( part[ j ] == str[ i + j ] ) {
				tf = 1;	
			}
			else {
				tf = 0;
				break;
			}
			j += 1;
		}
		if (tf == 1 ) {
			return i;
		}
		i += 1;
	}
}

void prnt( const char *s ) {
	int i;
	for( i=0 ; s[i] != '\0'; i++ )
		putchar( s[i] );
}
